
<?php


 require_once("../config.inc.php");
//require_once("../includes/db.class.php");
require_once("../classes/class.payment.php");
require_once('../includes/mailer.class.php');
require_once('../classes/class.mailshots.php');
$paypal = new objPayment;
$discount = new objDiscount;

$discount->useDiscount($UserID);


$replyy = date("Y-m-d h:i:s")." -> "; //date for log file

// create vars for POST data
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$business = $_POST['business'];
$item_name = $_POST['item_name'];
$invoice = $_POST['invoice'];
$payment_status = $_POST['payment_status'];
$txn_type = $_POST['txn_type'];
$subscr_date = $_POST['subscr_date'];
//$subscr_effective = $_POST['subscr_effective'];
//$period1 = $_POST['period1'];
//$period2 = $_POST['period2'];
//$period3 = $_POST['period3'];
//$amount1 = $_POST['amount1'];
//$amount2 = $_POST['amount2'];
//$amount3 = $_POST['amount3'];
//$mc_amount1 = $_POST['mc_amount1'];
//$mc_amount2 = $_POST['mc_amount2'];
//$mc_amount3 = $_POST['mc_amount3'];
//$recurring = $_POST['recurring'];
//$reattempt = $_POST['reattempt'];
//$retry_at = $_POST['retry_at'];
//$recur_times = $_POST['recur_times'];
//$username = $_POST['username'];
//$password = $_POST['password'];
//$subscr_id = $_POST['subscr_id'];

////////////////////////////////////////////////////////////////
//// PAYPAL POST VERIFICATION /////
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';

//form POST string
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}

// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
//$fp = fsockopen ('www.eliteweaver.co.uk', 80, $errno, $errstr, 30); // IPN testing URL - do not remove


if (!$fp) {
	// HTTP ERROR
	$replyy .= "HTTP ERROR | $payer_email | $txn_type | $invoice";
} else {
	fputs ($fp, $header . $req);
	while (!feof($fp)) {
		$res = fgets ($fp, 1024);
		if (strcmp ($res, "VERIFIED") == 0) {

		// check that receiver_email is  Primary PayPal email
		if ($paypal->businessID != $receiver_email && $paypal->businessID != $business) {
			exit ;
		}

		// prepare event vars for DB
		$userID1 = explode("_",$invoice);
		$userID = $userID1[0];
		$subscrPeriod = $userID1[1];
		$subscr_type = $userID1[3];
		$subscrTime = time();
		$subscrID = $invoice;

		switch ($txn_type)   {
			case "subscr_payment":
			//case "subscr_modify":
			case "subscr_signup":
				$activateSubscr = 1;
				//mail 2 us about new subscriber
				$mailshot = new objMailshot();
				$mailshot->subscrNotify($payer_email,$userID,$subscrTime,$subscrPeriod,"subscr_new","PayPal"); // sends an email
				//make discount inactive if user used it
                $discount->deactivateDiscount($userID);
				break;
			case "subscr_eot":
			case "subscr_failed":
			case "subscr_cancel":
			default:
				$activateSubscr = 0;
				break;
		}

		//check if DB record for this user exists
			$recordSet = $paypal->db->Execute("SELECT * FROM fa_subscriptions WHERE user_id='$userID' and subscr_id='$invoice'");
		if ($recordSet) {
			while (!$recordSet->EOF) {
				$recordSet->MoveNext();
			}
		}
		$cnter = $recordSet->RecordCount();


	        // insert or update subscription db record
		    if($cnter>0 ) {
				$recordSet = $paypal->db->Execute("UPDATE fa_subscriptions SET subscr_status='$txn_type',subscr_type='$subscr_type',subscr_time='$subscrTime',subscr_active='$activateSubscr',subscr_period='$subscrPeriod' WHERE user_id='$userID' and subscr_id='$invoice'");
			} else {
				if ($txn_type=="subscr_payment" || $txn_type=="subscr_failed" || $txn_type=="subscr_cancel")
		        $recordSet = $paypal->db->Execute("INSERT INTO `fa_subscriptions` (user_id,subscr_id,subscr_time,subscr_status,subscr_type,subscr_active,subscr_period) VALUES('$userID','$subscrID','$subscrTime','$txn_type','$subscr_type','$activateSubscr','$subscrPeriod')");
			}

	        $response = "VERIFIED";

			//loop through the $_POST array and print all vars to the screen.
			/*
			foreach($_POST as $key => $value){
				echo $key." = ". $value."<br>";
			}
			*/

		}
		else if (strcmp ($res, "INVALID") == 0) {
			$response = "INVALID";
	  	}

	}
	fclose ($fp);
}
//////////////////////////////////////////////////////////////




//////////////////////////////////////////////////////////////
//// LOG ALL EVENTS ////
$replyy .= "IPN $response | $payer_email | $txn_type | $invoice | $cnter | $info | $subscrID";
$fd = fopen("../logs/ipn.log", "a");
fwrite($fd, $replyy."\r\n");
fclose($fd);


//echo "test";

?>
